package com.example.cola.domain.service;

import com.example.cola.domain.model.Email;
import com.example.cola.domain.model.PhoneNumber;
import com.example.cola.domain.model.User;
import com.example.cola.domain.repository.UserRepository;
import org.springframework.stereotype.Service;

/**
 * 用户领域服务
 * 
 * @author 资深开发专家
 * @version 1.0
 */
@Service
public class UserDomainService {
    
    private final UserRepository userRepository;
    
    public UserDomainService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    /**
     * 检查用户注册的合法性
     */
    public void validateUserRegistration(Email email, PhoneNumber phoneNumber) {
        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(email)) {
            throw new IllegalArgumentException("邮箱已被注册");
        }
        
        // 检查手机号是否已存在
        if (phoneNumber != null && userRepository.existsByPhoneNumber(phoneNumber)) {
            throw new IllegalArgumentException("手机号已被注册");
        }
    }
    
    /**
     * 检查用户登录的合法性
     */
    public User validateUserLogin(String loginId, String password) {
        User user = null;
        
        // 尝试通过邮箱查找用户
        if (loginId.contains("@")) {
            Email email = Email.of(loginId);
            user = userRepository.findByEmail(email).orElse(null);
        } else {
            // 尝试通过手机号查找用户
            PhoneNumber phoneNumber = PhoneNumber.of(loginId);
            user = userRepository.findByPhoneNumber(phoneNumber).orElse(null);
        }
        
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        if (!user.isAvailable()) {
            throw new IllegalArgumentException("用户已被禁用");
        }
        
        if (!user.checkPassword(password)) {
            throw new IllegalArgumentException("密码错误");
        }
        
        return user;
    }
    
    /**
     * 检查用户更新信息的合法性
     */
    public void validateUserUpdate(User user, String name, PhoneNumber phoneNumber) {
        if (name != null && name.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }
        
        if (phoneNumber != null) {
            // 检查手机号是否已被其他用户使用
            User existingUser = userRepository.findByPhoneNumber(phoneNumber).orElse(null);
            if (existingUser != null && !existingUser.getId().equals(user.getId())) {
                throw new IllegalArgumentException("手机号已被其他用户使用");
            }
        }
    }
}
